package com.usermanage.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;

import com.usermanage.bean.User;
import com.usermanage.dao.UserDao;
import com.usermanage.tool.DBTool;
import com.usermanage.tool.Page;

/**
 * 数据库访问接口实现类
 * @author 陆贝伊
 *
 */
public class UserDaoImpl implements UserDao{
	/**
	 * 查询总页数
	 */
	@Override
	public long querytotalCount() {
		//声明一个变量存结果
		long totalCount=0;
		try {
			String sql="select count(id) as idcount from user";
			System.out.println("开始查询总条数");
			Map<String, Object> map1=DBTool.qr.query(sql, new MapHandler());
			System.out.println("查询完成");
			totalCount=(long)map1.get("idcount");
		} catch (Exception e) {
			// TODO: handle exception
		}
		System.out.println("查询到的总条数为"+totalCount);
		return totalCount;
	}
	/**
	 * 根据页数查询所有数据
	 */
	@Override
	public List<User> show(Page p) {
		//准备sql语句
		String sql="select id,name,phone,address from user limit ?,?";
		List<User> wlist=new ArrayList<User>();
		try {
			wlist=DBTool.qr.query(sql, new BeanListHandler<User>(User.class),p.getStart(),p.getCurrCount());
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
		return wlist;
	}
	/**
	 * 添加数据
	 */
	@Override
	public int add(User u) {
		int res=0;
		//准备sql语句
		String sql="insert into user(name,phone,address) value(?,?,?);";
		try {
			res=DBTool.qr.update(sql,u.getName(),u.getPhone(),u.getAddress());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return res;
	}
	/**
	 * 修改联系人
	 * @param u
	 * @return
	 */
	@Override
	public int edit(User u) {
		int res=0;
		//准备sql语句
		String sql="update user set phone=?,address=? where id=?";
		try {
			res=DBTool.qr.update(sql,u.getPhone(),u.getAddress(),u.getId());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return res;
	}
	/**
	 * 查找联系人
	 * @param id
	 * @return
	 */
	@Override
	public User queryById(String id) {
		//准备sql语句
		String sql="select id,name,phone,address from user where id=?";
		User u=null;
		try {
			u=DBTool.qr.query(sql, new BeanHandler<User>(User.class),id);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("查询到用户"+u);
		return u;
	}
	/**
	 * 删除联系人
	 */
	@Override
	public int delete(String id) {
		int res=0;
		//准备sql语句
		String sql="delete from user where id=?";
		try {
			res=DBTool.qr.update(sql,id);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return res;
	}

}
